package com.yuanda.wordhot.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yuanda.wordhot.entity.RoleEntity;
import com.yuanda.wordhot.entity.UserEntity;
import com.yuanda.wordhot.repository.UserRepository;

/**
 * @author YuBai
 * @since 2013-3-22
 * @Description 自定义的权限
 * @version 1.0
 */
@Service("customRealm")
public class CustomRealm extends AuthorizingRealm {
	@Autowired
	private UserRepository userRepository;
	
	
	public CustomRealm() {
//		setName("CustomRealm"); // This name must match the name in the User
//								// class's getPrincipals() method
//		setCredentialsMatcher(new HashedCredentialsMatcher());
	}
	
	
	public CustomRealm(UserRepository userRepository) {
		super();
		this.userRepository = userRepository;
	}


	/**
	 * 获取权限信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		Long userId = (Long) principals.fromRealm(getName()).iterator().next();
		UserEntity user = userRepository.get(userId);
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for (RoleEntity role : user.getRoles()) {
				info.addRole(role.getRoleName());
				info.addStringPermissions(role.getPermissions());
			}
			return info;
		} else {
			return null;
		}
	}

	/**
	 * 获取用户信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		UserEntity user = userRepository.findUserByEmail(token.getUsername());
		if (user != null) {
			return new SimpleAuthenticationInfo(user.getUserId(),
					user.getPassword(), getName());
		} else {
			return null;
		}
		
	}

}
